package com.sgl.retrofitdemo.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.orhanobut.logger.Logger;
import com.sgl.retrofitdemo.RetrofitApplication;

import java.util.Locale;

/**
 * Created by sunqiyong on 2016/11/13.
 */

public class RetrofitSystemUtils {
    public static int NETWORK_STATE_NOT_CONNECTED = 0;//网络未连接
    public static int NETWORK_STATE_CONNECT_WITH_WIF = 1;//连接了WiFi
    public static int NETWORK_STATE_CONNECT_WITH_MOBILE = 2;//连接了运营商网络

    /**
     * @param c
     * @return 网络是否可用
     */
    public static boolean isNetworkAvailable(Context c) {
        return getNetworkState(c) != NETWORK_STATE_NOT_CONNECTED;
    }

    /**
     * @param c
     * @return 获得当前网络状态
     */
    public static int getNetworkState(Context c) {
        try {
            int state = NETWORK_STATE_NOT_CONNECTED;
            ConnectivityManager manager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager == null) {
                return state;
            }
            NetworkInfo networkinfo = manager.getActiveNetworkInfo();
            if (networkinfo == null || !networkinfo.isAvailable()) {
                return NETWORK_STATE_NOT_CONNECTED;
            }
            if (networkinfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                return NETWORK_STATE_CONNECT_WITH_MOBILE;
            } else if (networkinfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return NETWORK_STATE_CONNECT_WITH_WIF;
            }
            return state;
        } catch (Exception e) {
            return NETWORK_STATE_NOT_CONNECTED;
        }
    }


    /**
     * 隐藏软键盘
     *
     * @param view
     */
    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 显示软键盘
     *
     * @param et
     */
    public static void showKeyboard(EditText et) {
        InputMethodManager imm = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 获取系统语言
     * <p>
     * zh 中文
     * zh_tw 中文(繁体)
     * en 英文
     * jp 日语
     * kr 韩语
     * fr 法文
     *
     * @return
     */
    public static void getSystemLanguage(Context context) {
        String language = Locale.getDefault().getLanguage();
        String country = Locale.getDefault().getCountry();

        Logger.d("language://" + language + "//country:" + country);
        String lan = "zh";
        if (language.equals("zh") && (country.equals("TW") || country.equals("HK"))) {
            lan = "zh_tw";
        } else if (language.equals("en") || language.equals("fr")) {
            lan = language;
        } else if (language.equals("ja")) {
            lan = "jp";
        } else if (language.equals("ko")) {
            lan = "kr";
        }
        SharedPrefUtil.instance(context).putString(RetrofitConst.SHARED_PREF_KEY_LANGUAGE, lan);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *
     * @param context
     * @param dpValue dp值
     * @return int 转化后的像素值
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String getVerison(Context me) {
        if (null != me) {
            PackageManager manager = me.getPackageManager();
            try {
                PackageInfo info = manager.getPackageInfo(me.getPackageName(), 0);
                return info.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 调用系统功能拨打电话
     *
     * @param act
     * @param phone
     */
    public static final String DAIL_SUSPEND = ";";

    public static void openSysCall(Context context, String... phone) {
        if (null != context && phone != null) {
            if (ContextCompat.checkSelfPermission(
                    context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                try {
                    String target = "";
                    for (int i = 0; i < phone.length; i++) {
                        target += (phone[i] + DAIL_SUSPEND);
                    }
                    target = target.substring(0, target.lastIndexOf(DAIL_SUSPEND));
                    Uri uri = Uri.parse("tel:" + target);
                    Intent intent = new Intent(Intent.ACTION_CALL, uri);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                } catch (Exception e) {
                    Logger.e(" " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return;
    }

    public static final int parseToInt(String value, int defaultVal) {
        if (null == value || 0 == value.trim().length()) {
            return defaultVal;
        }

        int result = defaultVal;
        try {
            result = Integer.parseInt(value.trim());
        } catch (Exception e) {
            try {
                result = (int) Float.parseFloat(value.trim());
            } catch (Exception e1) {
                result = defaultVal;
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 启动拨号界面
     * @param act
     * @param phone
     */
    public static void openSysCall(Activity act, String... phone) {
        if (null != act && phone != null) {
            if (ContextCompat.checkSelfPermission(
                    act, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                try {
                    String target = "";
                    for (int i = 0; i < phone.length; i++) {
                        target += (phone[i] + DAIL_SUSPEND);
                    }
                    target = target.substring(0, target.lastIndexOf(DAIL_SUSPEND));
                    Uri uri = Uri.parse("tel:" + target);
                    Intent intent = new Intent(Intent.ACTION_CALL, uri);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    act.startActivity(intent);
                } catch (Exception e) {
                    Logger.e(" " + e.getMessage());
                    e.printStackTrace();
                }
            } else {
                ActivityCompat.requestPermissions(act,
                        new String[]{Manifest.permission.CALL_PHONE},
                        RetrofitConst.REQUEST_CALL_PERMISSION_CODE);
            }
        }
        return;
    }

    /**
     * 设备唯一标识
     * @param context
     * @return
     */
    public static String getUdId(Context context){
        StringBuffer udid = new StringBuffer();

        TelephonyManager mTelephonyManager = (TelephonyManager) RetrofitApplication.getInstance().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = mTelephonyManager.getDeviceId();
        String androidId = Settings.Secure.getString(RetrofitApplication.getInstance().getApplicationContext().getContentResolver(),Settings.Secure.ANDROID_ID);
        if(!TextUtils.isEmpty(deviceId)){
            udid.append(deviceId);
        }
        if(!TextUtils.isEmpty(androidId)){
            udid.append(androidId);
        }
        if(udid != null){
            return SafetyUtil.encryptStringToMd5(udid.toString(),"32");
        }else{
            return "";
        }
    }
}
